package com.aaron.kjviewutils;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aaron.kjviewutils.eventBus.ConEventMsg;
import com.aaron.kjviewutils.eventBus.EventBusMsg;
import com.aaron.kjviewutils.retrofit.service.AccountService;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 作者：Aaron on 2017/2/16 11:39
 * 邮箱：kaijin.fang@edianniu.com
 */
public class LoginActivty extends BaseActivity {

    @Bind(R.id.loginToolBar)
    Toolbar loginToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.loginLogo)
    ImageView loginLogo;
    @Bind(R.id.contorlL)
    LinearLayout contorlL;

    private FragmentManager fragmentManager;
    private FragmetLogin fragmetLogin;
    private FragmentRegister fragmentRegister;
    private AccountService accountService;
    private Call<ResponseBody> callReRegister;
    private Call<AccountBean> callReLogin;

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        closeSelf(LoginActivty.this);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        //super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(EventBusMsg msg)
    {
        switch (msg.getType())
        {
            case PRE_REGISTER:
            {
                if(null!=loginToolBar)
                {
                    loginToolBar.setTitle("");
                    barTitle.setText("用户注册");
                }
                //切换到注册
                if(null!=fragmentManager)
                {
                    /*if (!fragmentRegister.isAdded()) { // 先判断是否被add过
                        fragmentManager.beginTransaction().hide(fragmetLogin)
                                .add(R.id.contorlL, fragmentRegister).commit(); // 隐藏当前的fragment，add下一个到Activity中
                    } else {
                        fragmentManager.beginTransaction().hide(fragmetLogin).show(fragmentRegister).commit(); // 隐藏当前的fragment，显示下一个
                    }*/
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    fragmentTransaction.replace(R.id.contorlL, fragmentRegister);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
                }
            }
            break;
            case PRE_LOGIN:
            {
                if(null!=loginToolBar)
                {
                    loginToolBar.setTitle("");
                    barTitle.setText("用户登录");
                }
                //切换到登录
                if(null!=fragmentManager)
                {
                    /*if (!fragmetLogin.isAdded()) { // 先判断是否被add过
                        fragmentManager.beginTransaction().hide(fragmentRegister)
                                .add(R.id.contorlL, fragmetLogin).commit(); // 隐藏当前的fragment，add下一个到Activity中
                    } else {
                        fragmentManager.beginTransaction().hide(fragmentRegister).show(fragmetLogin).commit(); // 隐藏当前的fragment，显示下一个
                    }*/
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    fragmentTransaction.replace(R.id.contorlL, fragmetLogin);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
                }
            }
            break;
            case CLOSE:
            {
                //关闭界面
                closeSelf(LoginActivty.this);
            }
            break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 80)
    public void onEvent(ConEventMsg msg)
    {
        switch (msg.getType())
        {
            case DO_REGISTER:
            {
                eventBus.removeStickyEvent(msg);
                //执行注册
                if(null!=retrofit)
                {
                    AccountBean account = (AccountBean) msg.getObj();
                    accountService = retrofit.create(AccountService.class);
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("username", account.result.username);
                    map.put("password", account.result.password);
                    map.put("email", account.result.email);
                    callReRegister = accountService.register(map);
                    mHandler.post(runnableRegister);
                }
            }
            break;
            case DO_LOGIN:
            {
                eventBus.removeStickyEvent(msg);
                //执行注册
                if(null!=retrofit)
                {
                    AccountBean account = (AccountBean) msg.getObj();
                    accountService = retrofit.create(AccountService.class);
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("username", account.result.username);
                    map.put("password", account.result.password);
                    callReLogin = accountService.login(map);
                    mHandler.post(runnableLogin);
                }
            }
            break;
            default:
                break;
        }
    }

    Runnable runnableRegister = new Runnable() {
        @Override
        public void run() {
            if(null!=callReRegister)
            {
                callReRegister.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        callReRegister.cancel();
                        AccountBean.Register register = null;
                        try {
                            Gson gson = new Gson();
                            register = gson.fromJson(response.body().string(), new TypeToken<AccountBean.Register>() {
                            }.getType());
                            if ("200".equals(register.retCode)) {
                                Toast.makeText(LoginActivty.this, "注册成功", Toast.LENGTH_SHORT).show();
                                saveUid(register.result);
                                eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.PRE_LOGIN));

                            } else {
                                Toast.makeText(LoginActivty.this, register.msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (IOException e)
                        {
                            Toast.makeText(LoginActivty.this, register.msg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        callReRegister.cancel();
                        Toast.makeText(LoginActivty.this, "注册失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    };

    Runnable runnableLogin = new Runnable() {
        @Override
        public void run() {
            if(null!=callReLogin)
            {
                callReLogin.enqueue(new Callback<AccountBean>() {
                    @Override
                    public void onResponse(Call<AccountBean> call, Response<AccountBean> response) {
                        callReLogin.cancel();
                        AccountBean account = response.body();
                        if ("200".equals(account.retCode)) {
                            Toast.makeText(LoginActivty.this, "登录成功", Toast.LENGTH_SHORT).show();
                            eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.CLOSE));
                            saveAccount(account);
                        } else {
                            Toast.makeText(LoginActivty.this, account.msg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<AccountBean> call, Throwable t) {
                        callReLogin.cancel();
                        Toast.makeText(LoginActivty.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_login);
        ButterKnife.bind(this);
        fragmentManager = this.getSupportFragmentManager();
        fragmetLogin = new FragmetLogin();
        fragmentRegister = new FragmentRegister();

        initTitle();
        initContent();
    }

    private void initContent()
    {
        Glide.with(LoginActivty.this).load("http://www.mob.com/images/logo.png").animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(loginLogo);
        //初始化加载登录模块
        if(null!=fragmentManager)
        {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.contorlL, new FragmetLogin());
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        }
    }

    private void initTitle()
    {
        loginToolBar.setTitle("");
        barTitle.setText("用户登录");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        loginToolBar.setNavigationIcon(null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            //关闭
            closeSelf(LoginActivty.this);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableRegister);
            mHandler.removeCallbacks(runnableLogin);
        }
        if(null!=callReLogin)
        {
            callReLogin.cancel();
        }
        if(null!=callReRegister)
        {
            callReRegister.cancel();
        }
        ButterKnife.unbind(this);
    }
}
